import { Action, fromJwt, fromParam, fromResponse, JwtPayload, JwtPayloadDto, PermissionsTo } from '@boticord/auth'
import { ResourceUp, UpResourceDto } from '@boticord/resources-client'
import { Body, Controller, InternalServerErrorException, Param, Post, Req } from '@nestjs/common'
import { UpsService } from '../services/ups.service'
import { AnalyseRequest, EventTypes, getIp } from '@boticord/analytics'
import { ErrorCodes } from '@boticord/consts'
import { FastifyRequest } from 'fastify'

@Controller('ups')
export class UpsController {
  constructor(
    private readonly ups: UpsService,
  ) {}

  @Post(':resource')
  @PermissionsTo(Action.Create, ResourceUp)
  @AnalyseRequest(EventTypes.UpAdded, {
    affected: fromParam('resource'),
    user: fromJwt('id'),
    extract: fromResponse('upCount'),
  })
  async up(
    @Param('resource') resourceID: string,
    @JwtPayload() jwt: JwtPayloadDto,
    @Body() body: UpResourceDto,
    @Req() req: FastifyRequest,
  ) {
    const ip = getIp(req.headers)
    if (!ip) throw new InternalServerErrorException({ code: ErrorCodes.CannotDetectIp })
    return await this.ups.up(jwt.id, resourceID, body, ip)
  }

  // can't delete up because it's not implemented in the client
  // @Delete(':resource')
  // @PermissionsTo(Action.Create, ResourceUp, { fetch: { id: fromParam('resource') } })
  // @AnalyseRequest(EventTypes.UpRemoved, fromParam('resource'))
  // async unup(@Param('resource') resourceID: string, @JwtPayload() jwt: JwtPayloadDto) {
  //   await this.ups.unup(jwt.id, resourceID)
  // }
}